﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Clarity.Phone.Controls.Animations;
using Microsoft.Phone.Controls;

namespace TradeMo
{
    public interface ISearchResultsView
    {
        void SetLastSearchResultItem(SearchResultItem item);
    }

    public partial class SearchResultsView : ISearchResultsView
    {
        private GeneralSearchCriteriaView _generalSearchCriteriaView;
		private CriteriaBikesView _criteriaBikesView;
		private CriteriaUsedCarsView _criteriaUsedCarsView;
        private CriteriaBoatsView _criteriaBoatsView;
        private CriteriaJobsView _criteriaJobsView;
        private CriteriaPropertyForSaleView _criteriaPropertyForSaleView;
        private CriteriaPropertyRentalView _criteriaPropertyRentalView;
        private CriteriaPropertyForSaleView _criteriaPropertyOpenHomeView;
        private CriteriaPropertyFlatmateView _criteriaPropertyFlatmateView;
        private readonly SearchResultsViewModel _viewModel;
        private readonly Popup _searchCriteriaPopup = new Popup();
        private string _searchType;
        private string _criteriaHash;

        public SearchResultsView()
        {
            InitializeComponent();
            _viewModel = new SearchResultsViewModel(this);
            DataContext = _viewModel;
            AnimationContext = LayoutRoot;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_searchType != null) return;    // Already loaded

            NavigationContext.QueryString.TryGetValue("type", out _searchType);
            NavigationContext.QueryString.TryGetValue("criteria", out _criteriaHash);

            if (string.IsNullOrEmpty(_searchType) ||
                string.IsNullOrEmpty(_criteriaHash))
                NavigationService.GoBack();

            if (!_viewModel.BeginSearch(_searchType, _criteriaHash))
                NavigationService.GoBack();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (_searchCriteriaPopup.IsOpen)
            {
                IBackButtonController backButtonController = _searchCriteriaPopup.Child as IBackButtonController;
				if (backButtonController != null && !backButtonController.CanClose())
				{
					e.Cancel = true;
					backButtonController.CloseChild();
					return;
				}

				if (backButtonController != null)
				{
					backButtonController.Close(() =>
							{
								_searchCriteriaPopup.IsOpen = false;
								VisualStateManager.GoToState(this, "EnabledState", true);
							});
				}
				else
				{
					_searchCriteriaPopup.IsOpen = false;
					VisualStateManager.GoToState(this, "EnabledState", true);
				}
            	e.Cancel = true;
                return;
            }
            base.OnBackKeyPress(e);
        }


        private void DidYouMeanText_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _viewModel.ChangeSearchToDidYouMean();
        }

        private void ResultsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ResultsListBox.SelectedItem == null) return;

            var selectedItem = ResultsListBox.SelectedItem as SearchResultItem;
            ResultsListBox.SelectedItem = null;

            if (selectedItem == null) return;

            if (selectedItem == SearchResultsViewModel.LoadMore)
                _viewModel.DoSearchMore();
            else
                OpenListing(selectedItem.Listing.ListingId);
        }

        private void OpenListing(int listingId)
        {
            NavigationService.Navigate(new Uri("/ListingView.xaml?ListingId=" + listingId, UriKind.Relative));
        }

        private void GestureListener_Hold(object sender, GestureEventArgs e)
        {
            return;
        }

        private void GestureListener_Tap(object sender, GestureEventArgs e)
        {
            VisualStateManager.GoToState(this, "DisabledState", true);
            switch (_viewModel.SelectedSearchTypeSelector.Item)
            {
                case SearchType.General:
                    _generalSearchCriteriaView = new GeneralSearchCriteriaView(_viewModel.GeneralSearchCriteriaModel);
                    _generalSearchCriteriaView.RefreshAction = () =>
                    {
                        _generalSearchCriteriaView.Close(() => _searchCriteriaPopup.IsOpen = false);

                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _generalSearchCriteriaView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

				case SearchType.Bikes:
					_criteriaBikesView = new CriteriaBikesView(_viewModel.CriteriaBikesModel);
            		_criteriaBikesView.RefreshAction = () =>
            		        {
								_criteriaBikesView.Close( () => _searchCriteriaPopup.IsOpen = false);
								VisualStateManager.GoToState(this, "EnabledState", true);
								_viewModel.DoSearch();
            		        };
            		_searchCriteriaPopup.Child = _criteriaBikesView;
            		_searchCriteriaPopup.IsOpen = true;
            		break;

				case SearchType.UsedCars:
					_criteriaUsedCarsView = new CriteriaUsedCarsView(_viewModel.CriteriaUsedCarsModel);
            		_criteriaUsedCarsView.RefreshAction = () =>
            				{
								_criteriaUsedCarsView.Close( () => _searchCriteriaPopup.IsOpen = false);
            					VisualStateManager.GoToState(this, "EnabledState", true);
								_viewModel.DoSearch();
            				};
            		_searchCriteriaPopup.Child = _criteriaUsedCarsView;
            		_searchCriteriaPopup.IsOpen = true;
            		break;

                case SearchType.Boats:
                    _criteriaBoatsView = new CriteriaBoatsView(_viewModel.CriteriaBoatsModel);
                    _criteriaBoatsView.RefreshAction = () =>
                    {
                        _criteriaBoatsView.Close(() => _searchCriteriaPopup.IsOpen = false);
                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _criteriaBoatsView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

                case SearchType.Jobs:
                    _criteriaJobsView = new CriteriaJobsView(_viewModel.CriteriaJobsModel);
                    _criteriaJobsView.RefreshAction = () =>
                    {
                        _criteriaJobsView.Close(() => _searchCriteriaPopup.IsOpen = false);
                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _criteriaJobsView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

                case SearchType.Residential:
                    _criteriaPropertyForSaleView = new CriteriaPropertyForSaleView(_viewModel.CriteriaPropertyForSaleModel);
                    _criteriaPropertyForSaleView.RefreshAction = () =>
                    {
                        _criteriaPropertyForSaleView.Close(() => _searchCriteriaPopup.IsOpen = false);
                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _criteriaPropertyForSaleView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

                case SearchType.Rental:
                    _criteriaPropertyRentalView = new CriteriaPropertyRentalView(_viewModel.CriteriaPropertyRentalModel);
                    _criteriaPropertyRentalView.RefreshAction = () =>
                    {
                        _criteriaPropertyRentalView.Close(() => _searchCriteriaPopup.IsOpen = false);
                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _criteriaPropertyRentalView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

                case SearchType.OpenHomes:
                    _criteriaPropertyOpenHomeView = new CriteriaPropertyForSaleView(_viewModel.CriteriaPropertyOpenHomeModel);
                    _criteriaPropertyOpenHomeView.RefreshAction = () =>
                    {
                        _criteriaPropertyOpenHomeView.Close(() => _searchCriteriaPopup.IsOpen = false);
                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _criteriaPropertyOpenHomeView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

                case SearchType.Flatmates:
                    _criteriaPropertyFlatmateView = new CriteriaPropertyFlatmateView(_viewModel.CriteriaPropertyFlatmateModel);
                    _criteriaPropertyFlatmateView.RefreshAction = () =>
                    {
                        _criteriaPropertyFlatmateView.Close(() => _searchCriteriaPopup.IsOpen = false);
                        VisualStateManager.GoToState(this, "EnabledState", true);
                        _viewModel.DoSearch();
                    };
                    _searchCriteriaPopup.Child = _criteriaPropertyFlatmateView;
                    _searchCriteriaPopup.IsOpen = true;
                    break;

                default:
                    MessageBox.Show("No additional options for " + _viewModel.SelectedSearchTypeSelector.Title + " search");
                    VisualStateManager.GoToState(this, "EnabledState", true);
                    break;
            }
        }

        public void SetLastSearchResultItem(SearchResultItem item)
        {
            ResultsListBox.ScrollIntoView(item);
        }
    }
}